﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;

namespace BOMS.Utility
{
   
        /// <summary>
        ///	说明： xml结构文档的构建帮助类
        /// 创建：朱晓华 2009-9-9
        /// -------------------------------
        /// 修改:
        ///		添加长度验证参数 2009-9-10
        /// </summary>
        public class XmlHelper
        {
            private readonly XmlDocument _doc;
            private readonly XmlNode _root;

            public XmlHelper()
                : this("DATA")
            {
            }

            public XmlHelper(string rootTag)
            {
                _doc = new XmlDocument();
                _doc.LoadXml("<" + rootTag + "></" + rootTag + ">");
                _root = _doc.DocumentElement;
            }

            #region 添加节点
            /// <summary>
            /// （在根节点下）添加子节点
            /// </summary>
            /// <param name="tag">标记名</param>
            /// <returns></returns>
            public XmlNode AddTextNode(string tag)
            {
                return AddTextNode(_root, tag, string.Empty);
            }
            /// <summary>
            /// （在根节点下）添加子节点,并赋innerText值
            /// </summary>
            /// <param name="tag">标记名</param>
            /// <param name="innerText">内容</param>
            /// <returns></returns>
            public XmlNode AddTextNode(string tag, string innerText)
            {
                return AddTextNode(_root, tag, innerText);
            }
            /// <summary>
            /// （在根节点下）添加子节点,并赋innerText值
            /// </summary>
            /// <param name="tag">标记名</param>
            /// <param name="innerText">内容</param>
            /// <param name="Caption">标记说明（中文提示）</param>
            /// <param name="Maxlength">内容最多字符数</param>
            /// <returns></returns>
            public XmlNode AddTextNode(string tag, string innerText, string Caption, int Maxlength)
            {
                return AddTextNode(_root, tag, innerText, Caption, Maxlength);
            }
            /// <summary>
            /// 添加子节点
            /// </summary>
            /// <param name="parentNode">（要添加的子节点的）父节点</param>
            /// <param name="tag">子节点标签</param>
            /// <returns></returns>
            public XmlNode AddTextNode(XmlNode parentNode, string tag)
            {
                return AddTextNode(parentNode, tag, string.Empty);
            }
            /// <summary>
            /// 添加子节点
            /// </summary>
            /// <param name="parentNode">父节点</param>
            /// <param name="tag">标记名</param>
            /// <param name="innerText">内容</param>
            /// <returns>生成的新标记</returns>
            public XmlNode AddTextNode(XmlNode parentNode, string tag, string innerText)
            {
                return AddTextNode(parentNode, tag, innerText, null, 0);
            }
            /// <summary>
            /// 添加子节点
            /// </summary>
            /// <param name="parentNode">父节点</param>
            /// <param name="tag">标记名</param>
            /// <param name="innerText">内容</param>
            /// <param name="Caption">标记提示语（中文友好提示），空字符串表示不检测</param>
            /// <param name="Maxlength">内容最大长度</param>
            /// <returns></returns>
            public XmlNode AddTextNode(XmlNode parentNode, string tag, string innerText,
                string Caption, int Maxlength)
            {
                XmlNode n = _doc.CreateElement(tag);
                if (!string.IsNullOrEmpty(Caption) && Maxlength > 0)
                {
                    if (innerText.Length > Maxlength)
                    {
                        throw new System.ArgumentOutOfRangeException(
                            tag, "“" + Caption + "”内容的字数不能超过" + Maxlength);
                    }
                }
                n.InnerText = innerText;
                parentNode.AppendChild(n);
                return n;
            }
            //public void AddAttribute(XmlNode parentNode,string AttributeName,string AttributeValue)
            //{
            //    XmlAttribute attr = null;
            //    attr = _doc.CreateAttribute(AttributeName);
            //        attr.Value =AttributeValue;
            //        parentNode.Attributes.SetNamedItem(attr);

            //}
            #endregion

            #region 格式化ToString
            public override string ToString()
            {
                return ToString(false);
            }

            /// <summary>
            /// 带有缩进、换行格式的XML字符串
            /// </summary>
            /// <param name="format">是否使用格式排版</param>
            /// <returns>经过转义之后的XML字符串</returns>
            public string ToString(bool format)
            {
                StringWriter sw = new StringWriter();
                using (XmlTextWriter writer = new XmlTextWriter(sw))
                {
                    if (format)
                    {
                        writer.Indentation = 4;// the Indentation
                        writer.Formatting = Formatting.Indented;
                    }
                    _doc.WriteContentTo(writer);
                    writer.Close();
                }
                return sw.ToString();
            }
            #endregion

            #region 静态方法
            /// <summary>
            /// 检查字符串是否含有xml中转义过的字符组合，如 ＆ａｍｐ；  ＆ｌｔ；等
            /// 创建：梁宁 2009-11-10
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static bool HasEscapedChar(string str)
            {
                Regex reg = new Regex("&amp;|&lt;|&gt;|&apos;|&quot;");
                return reg.IsMatch(str);
            }
            /// <summary>
            /// 是否有危险字符？（xml将必须对其转义，如：《，＆）
            /// 创建：梁宁 2009-11-10
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public static bool HasDangerChar(string input)
            {
                Regex reg = new Regex("<|&(?!amp;|lt;|gt;|apos;|quot;)");
                return reg.IsMatch(input);
            }
            /// <summary>
            /// 将文本转义,以免编制到xml文本中出错(按xml的语法要求)
            /// 创建：梁宁 2009-11-10
            /// </summary>
            /// <param name="Input"></param>
            /// <returns></returns>
            public static string Escape(string Input)
            {
                return Regex.Replace(Input, "&(?!amp;|lt;|gt;|apos;|quot;)", "&amp;", RegexOptions.Singleline)
                .Replace("<", "&lt;")
                .Replace(">", "&gt;")
                .Replace("'", "&apos;")
                .Replace("\"", "&quot;");
            }
            /// <summary>
            /// 将文本还原（仅处理因在xml中被转义的）
            ///	创建：梁宁 2009-11-10
            /// </summary>
            /// <param name="EscapedString"></param>
            /// <returns></returns>
            public static string Unescape(string EscapedString)
            {
                return Regex.Replace(EscapedString, "&amp;", "&", RegexOptions.Singleline)
                .Replace("&lt;", "<")
                .Replace("&gt;", ">")
                .Replace("&apos;", "'")
                .Replace("&quot;", "\"");
            }
            #endregion
        }
}
